﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ShenLanCMS.Models;
using PagedList;

namespace ShenLanCMS.Web.Controllers
{
    public class PostController : Controller
    {
        private EntityContext db = new EntityContext();

        //分页记录
        int pageSize = 10;
        [IsAdmin]
        public ViewResult Admin(int? page)
        {
            var index = (page ?? 1) - 1;
            ViewData["actionName"] = "Admin";
            var posts = db.Posts.Where(n => n.Status == 1).OrderByDescending(n => n.PubTime).ToPagedList(index, pageSize);
            return View(posts);
        }

        //所有分类
        public ViewResult AllType()
        {
            return View();
        }

        //根据分类查看文章
        public ActionResult ByType(int id, int? page)
        {
            var index = (page ?? 1) - 1;
            ViewData["actionName"] = "ByType";
            var type = db.PostTypes.Find(id);
            if (type == null)
                return Redirect("/");
            ViewData["type"] = type;
            var posts = db.Posts.Where(n => n.PostTypeID == id);

            foreach (var item in posts)
                ViewData["typename"] = item.GetPostType().TypeName;

            return View(posts.ToPagedList(index, pageSize));
        }

        //我的文章
        [IsAdmin]
        public ViewResult MyPost(int? page)
        {
            var index = (page ?? 1) - 1;
            ViewData["actionName"] = "MyPost";
            var user = Session["users"] as ShenLanCMS.Models.User;
            var posts = db.Posts.Where(n => n.AddUserID == user.UserID).OrderByDescending(n => n.PubTime).ToPagedList(index, pageSize);
            return View(posts);
        }

        //回收站的文章
        [IsAdmin]
        public ViewResult Recycle(int? page)
        {
            var index = (page ?? 1) - 1;
            ViewData["actionName"] = "Recycle";
            var posts = db.Posts.Where(n => n.Status == 0).OrderByDescending(n => n.PubTime).ToPagedList(index, pageSize);
            return View(posts);
        }

        //待审核的文章
        [IsAdmin]
        public ViewResult Approve(int? page)
        {
            var index = (page ?? 1) - 1;
            ViewData["actionName"] = "Approve";
            var posts = db.Posts.Where(n => n.Status == 0).OrderByDescending(n => n.PubTime).ToPagedList(index, pageSize);
            return View(posts);
        }

        //查看文章
        public ActionResult View(Guid id)
        {
            Post post = db.Posts.Find(id);

            //如文章不存在则返回首页        
            if (post == null || post.Status != 1)
            {
                return Redirect("/");
                //Response.Write("<script>alert('您查看的文章不存在,确定后返回首页');window.location.href='/';</script>");
            }

            //更新点击量
            var click=id.ToString() + "_click";
            if (Request.Cookies[click] == null)
            {
                try
                {
                    db.Entry(post).State = EntityState.Modified;
                    post.Click += 1;
                    db.SaveChanges();
                    HttpCookie cookie = new HttpCookie(click);
                    cookie.Expires.AddDays(1);
                    Response.AppendCookie(cookie);
                }
                catch { }
            }
            return View(post);
        }

        //顶踩文章
        [HttpPost]
        public ActionResult Dig()
        {
            try
            {
                var mod = Request.QueryString["mod"];
                var id = Guid.Parse(Request.QueryString["id"]);

                //查看是否已经顶或踩过
                var dig=id.ToString()+"_dig";
                if (Request.Cookies[dig] != null)
                    return Json("请不要重复顶或踩该文章!");

                var post = db.Posts.Find(id);
                db.Entry(post).State = EntityState.Modified;
                if (mod == "good")
                    post.DigGood += 1;
                else
                    post.DigBad += 1;
                db.SaveChanges();

                //cookies记录已经顶或踩过的文章
                var cookie = new HttpCookie(dig);
                cookie.Expires.AddDays(1);
                Response.AppendCookie(cookie);

                return Json("操作成功");
            }
            catch { return Json("操作失败"); }
        }

        //添加文章
        [IsAdmin]
        public ActionResult Add()
        {
            ViewBag.PostTypeID = new SelectList(db.PostTypes, "PostTypeID", "TypeName");
            return View();
        }

        //添加文章
        [IsAdmin]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(Post post, FormCollection fc)
        {          
            ViewBag.PostTypeID = new SelectList(db.PostTypes, "PostTypeID", "TypeName");
            var user = Session["users"] as ShenLanCMS.Models.User;

            if (ModelState.IsValid)
            {
                post.PostID = Guid.NewGuid();
                post.AddUserID = user.UserID;
                post.Click = 0;
                post.DigBad = 0;
                post.DigGood = 0;
                post.PubTime = DateTime.Now;
                //tag添加
                AddTags(post.Tag);
                post.Status = 1;

                db.Posts.Add(post);
                db.SaveChanges();
                ModelState.AddModelError("", "添加文章成功.");
                return View();
            }
            ModelState.AddModelError("", "添加文章失败,请确定您的输入完整.");
            return View(post);
        }

        //tag添加
        public void AddTags(string tag)
        {
            try
            {
                var tags = tag.Split(',');
                var ts = db.Tags;
                for (var i = 0; i < tags.Length; i++)
                {
                    var flag = true;
                    //判断数据库中是否已经存在
                    foreach (var item in ts)
                    {
                        if (item.TagName == tags[i])
                            flag = false;
                    }
                    if (flag)
                    {
                        var t = new Tag();
                        t.TagID = Guid.NewGuid();
                        t.TagName = tags[i];
                        t.Num = 1;
                        var sql = string.Format("insert into tags ([tagid],[tagname],[num]) values ('{0}','{1}','{2}')", t.TagID, t.TagName, t.Num);
                        var n = db.Database.ExecuteSqlCommand(sql);
                    }
                }
            }
            catch { }
        }

        [IsAdmin]
        public ActionResult Edit(Guid id)
        {

            Post post = db.Posts.Find(id);
            ViewData["PostTypeID"] = new SelectList(db.PostTypes, "PostTypeID", "TypeName", post.PostTypeID);
            return View(post);
        }

        [IsAdmin]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Post post)
        {
            if (ModelState.IsValid)
            {
                db.Entry(post).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Admin");
            }
            return View(post);
        }

        //放入回收站
        [IsAdmin]
        [HttpPost]
        public ActionResult Delete(Guid id)
        {
            try
            {
                Post post = db.Posts.Find(id);
                db.Entry(post).State = EntityState.Modified;
                post.Status = 0;
                db.SaveChanges();
                return Json("操作成功");
            }
            catch { return Json("操作失败"); }
        }

        //还原文章
        [IsAdmin]
        [HttpPost]
        public ActionResult RecyclePost(Guid id)
        {
            try
            {
                Post post = db.Posts.Find(id);
                db.Entry(post).State = EntityState.Modified;
                post.Status = 1;
                db.SaveChanges();
                return Json("操作成功");
            }
            catch { return Json("操作失败"); }
        }

        //彻底删除
        [IsAdmin]
        [HttpPost]
        public ActionResult DeleteRecycle(Guid id)
        {
            try
            {
                Post post = db.Posts.Find(id);
                db.Posts.Remove(post);
                db.SaveChanges();
                //同时也删除文章的评论
                var sql = string.Format("delete from comments where postid='{0}'", id);
                db.Database.ExecuteSqlCommand(sql);
                //var comments = db.Comments.Where(n => n.PostID == id);
                //if (comments.Count() > 0)
                //{
                //    foreach (var item in comments)
                //    {
                //        db.Comments.Remove(item);
                //        db.SaveChanges();
                //    }
                //}
                return Json("删除成功");
            }
            catch { return Json("删除失败"); }
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}